package com.loongxun.playwithyou.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.App;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.bean.Member;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.ui.adapter.Bee_PageAdapter;
import com.loongxun.playwithyou.util.DensityUtils;
import com.loongxun.playwithyou.util.ToastView;
import com.loongxun.playwithyou.view.MyDialog;
import com.loongxun.playwithyou.view.PageIndicator;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 陪玩人员详情
 * Created by Administrator on 2017/7/14.
 */
public class MemberInfoActivity extends Activity implements View.OnClickListener{

    private static final int REQUESTCODE = 8;

    private Context context;
    private SendRequest send;
    private Member member = new Member();
    private List<Member> evaluateList = new ArrayList<>();
    //用户编辑器
    private SharedPreferences share;
    private SharedPreferences.Editor editor;
    private String  user_id;

    private TextView tv_member_name,tv_member_dizhi,tv_member_duihao;
    private LinearLayout ll_info_layout;

    //banner控件、集合、适配器、、banner分页指示器
    private ViewPager bannerViewPager;
    private ArrayList<View> bannerListView;
    private Bee_PageAdapter bannerPageAdapter;
    private View mTouchTarget;
    private PageIndicator mIndicator;

    private ImageLoader imageLoader = ImageLoader.getInstance();
    private MyDialog mDialog;

    private LinearLayout ll_info_evaluate,ll_report_defriend;
    private TextView tv_report,tv_defriend;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_info);
        context = MemberInfoActivity.this;

        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();
        user_id = share.getString("user_id", "");
        if (!"".equals(user_id)) {
            initData(user_id);
        }

        member.setMember_id(getIntent().getIntExtra("member_id", 0));
        try {
            send = new SendRequest();
            send.memberId = member.getMember_id()+"";
            //陪玩人员详情
            nHttpClient.getAll(ApiInterface.INDEX_INFO, send.tofindShieldingJson().toString(), indexHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
        initView();
    }

    private void initData(String userId){
        try {
            send = new SendRequest();
            send.memberId = member.getMember_id()+"";
            send.userId = userId;
            //判断是不是被拉黑
            nHttpClient.getAll(ApiInterface.IS_SHIELD, send.tofindShieldingJson().toString(), shieldingHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.iv_info_right).setOnClickListener(this);
        ll_report_defriend = (LinearLayout) findViewById(R.id.ll_report_defriend);
        ll_report_defriend.setOnClickListener(this);
        tv_report = (TextView) findViewById(R.id.tv_report);
        tv_report.setOnClickListener(this);
        tv_defriend = (TextView) findViewById(R.id.tv_defriend);
        tv_defriend.setOnClickListener(this);

        findViewById(R.id.tv_coll).setOnClickListener(this);
        findViewById(R.id.tv_contact_service).setOnClickListener(this);
        findViewById(R.id.tv_all_evaluate).setOnClickListener(this);
        findViewById(R.id.tv_go_to_order).setOnClickListener(this);
        tv_member_name = (TextView) findViewById(R.id.tv_member_name);
        tv_member_dizhi = (TextView) findViewById(R.id.tv_member_dizhi);
        tv_member_duihao = (TextView) findViewById(R.id.tv_member_duihao);
        ll_info_layout = (LinearLayout) findViewById(R.id.ll_info_layout);
        ll_info_evaluate = (LinearLayout) findViewById(R.id.ll_info_evaluate);

        //获取首页banner控件
        bannerViewPager = (ViewPager)findViewById(R.id.banner_viewpager);
        //为控件添加样式
        ViewGroup.LayoutParams params = bannerViewPager.getLayoutParams();
        params.width = getDisplayMetricsWidth();
        params.height = (int) (params.width*4/3);
        bannerViewPager.setLayoutParams(params);
        //banner控件适配器
        bannerListView = new ArrayList<View>();
        bannerPageAdapter = new Bee_PageAdapter(bannerListView);
        bannerViewPager.setAdapter(bannerPageAdapter);
        bannerViewPager.setCurrentItem(0);
        bannerViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            private int mPreviousState = ViewPager.SCROLL_STATE_IDLE;
            @Override
            public void onPageScrolled(int i, float v, int i2) {}

            @Override
            public void onPageSelected(int i) {}

            @Override
            public void onPageScrollStateChanged(int state) {
                // All of this is to inhibit any scrollable container from consuming our touch events as the user is changing pages
                //所有这一切都是抑制任何可滚动的容器从消费我们的触摸事件在用户改变页面
                if (mPreviousState == ViewPager.SCROLL_STATE_IDLE) {
                    if (state == ViewPager.SCROLL_STATE_DRAGGING) {
                        mTouchTarget = bannerViewPager;
                    }
                } else {
                    if (state == ViewPager.SCROLL_STATE_IDLE || state == ViewPager.SCROLL_STATE_SETTLING) {
                        mTouchTarget = null;
                    }
                }
                mPreviousState = state;
            }
        });
        //banner分页指示器
        mIndicator = (PageIndicator)findViewById(R.id.indicator);
        mIndicator.setViewPager(bannerViewPager);
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.menu_main, menu);
//        return super.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.action_settings:
//               Toast.makeText(this,"0",Toast.LENGTH_SHORT).show();
//                return true;
//            default:
//                return super.onOptionsItemSelected(item);
//        }
//    }

    @Override
    public void onClick(View view) {
        Intent intent;
        user_id = share.getString("user_id", "");
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_info_right:
                if (isLogin(user_id)) {
                    initData(user_id);
                }
                if (ll_report_defriend.getVisibility() == View.VISIBLE) {
                    ll_report_defriend.setVisibility(View.GONE);
                }else {
                    ll_report_defriend.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.tv_report:
//                Toast.makeText(this,"举报成功，谢谢您的举报，我们的工作人员会尽快核实您的举报信息",Toast.LENGTH_SHORT).show();
                intent  = new Intent(this,ReportActivity.class);
                startActivity(intent);
                ll_report_defriend.setVisibility(View.GONE);
                break;
            case R.id.tv_defriend:
                //已拉黑
                if (!tv_defriend.getText().equals("拉黑")) {
                    try {
                        send = new SendRequest();
                        send.memberId = member.getMember_id()+"";
                        send.userId = user_id;
                        //取消拉黑
                        nHttpClient.getAll(ApiInterface.DEL_SHIELD, send.tofindShieldingJson().toString(), delShieldingHandler);
                    }catch (Exception e){
                        ToastView toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }else {
                    try {
                        send = new SendRequest();
                        send.memberId = member.getMember_id()+"";
                        send.userId = user_id;
                        //拉黑
                        nHttpClient.getAll(ApiInterface.SAVE_SHIELD, send.tofindShieldingJson().toString(), saveShieldingHandler);
                    }catch (Exception e){
                        ToastView toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }
                break;
            case R.id.tv_coll:
                if (isLogin(user_id)) {
                    try {
                        send = new SendRequest();
                        send.memberId = member.getMember_id() + "";
                        send.userId = user_id;
                        //陪玩详情页面收藏功能
                        nHttpClient.getAll(ApiInterface.COLL_MEMBER, send.toDelCollJson().toString(), memberHandler);
                    } catch (Exception e) {
                        ToastView toast = new ToastView(context, "参数错误");
                        toast.show();
                    }
                }
                break;
            case R.id.tv_contact_service:
                //判断Android版本是否是Android7.0以上
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){
                    //检查权限
                    if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(this,Manifest.permission.CALL_PHONE)) {
                            new AlertDialog.Builder(context)
                                    .setMessage("app需要开启权限才能使用此功能")
                                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                            intent.setData(Uri.parse("package:" + getPackageName()));
                                            startActivity(intent);
                                        }
                                    })
                                    .setNegativeButton("取消", null)
                                    .create()
                                    .show();
                        }
                    }else {
                        //申请权限
                        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CALL_PHONE},REQUESTCODE);
                    }
                }else{
                    call();
                }
                break;
            case R.id.tv_all_evaluate:
                if (isLogin(user_id)) {
                    intent = new Intent(context, EvaluateActivity.class);
                    intent.putExtra("member_id", member.getMember_id()+"");
                    startActivity(intent);
                }
                break;
            case R.id.tv_go_to_order:
                if (isLogin(user_id)) {
                    intent = new Intent(context, ToOrderActivity.class);
                    intent.putExtra("member_id", member.getMember_id());
                    startActivity(intent);
                }
                break;
            default:
                break;
        }
    }

    private boolean isLogin(String user_id) {
        if (user_id.equals("")){
            Intent intent = new Intent(context, LoginActivity.class);
            startActivityForResult(intent,0);
            return false;
        }
        return true;
    }

    private MyHttpClientRespenseHandler memberHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler indexHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            if (succeed == 1) {
                try {
                    List<String> imgs = null;
                    JSONObject subItemObject = json.getJSONObject("data").getJSONObject("member");
                    member.setMember_id(subItemObject.optInt("member_id", 0));
                    member.setClick_num(subItemObject.optInt("click_num", 0));
                    member.setMember_address(subItemObject.optString("member_address"));
                    member.setMember_img(subItemObject.optString("member_img"));
                    member.setMember_sex(subItemObject.optInt("member_sex", 0));
                    member.setMember_name(subItemObject.optString("member_name"));
                    itemArray = subItemObject.getJSONArray("memberIntroList");
                    if (itemArray != null){
                        imgs = new ArrayList<>();
                        for(int i = 0;i < itemArray.length();i++) {
                            JSONObject jsonObject = itemArray.getJSONObject(i);
                            imgs.add(jsonObject.optString("intro_img"));
                        }
                    }
                    member.setImgs(imgs);
                    itemArray = subItemObject.getJSONArray("memberGames");
                    if (itemArray != null){
                        imgs = new ArrayList<>();
                        for(int i = 0;i < itemArray.length();i++) {
                            JSONObject jsonObject = itemArray.getJSONObject(i);
                            imgs.add(jsonObject.optString("game_logo"));
                        }
                    }
                    member.setGameImgs(imgs);
                    itemArray = json.getJSONObject("data").getJSONArray("evaluateList");
                    evaluateList.clear();
                    for(int i = 0;i < itemArray.length();i++) {
                        JSONObject evaluateObject = itemArray.getJSONObject(i);
                        Member member1 = new Member();
                        member1.setEvaluateInfo(evaluateObject.getString("evaluateInfo"));
                        member1.setCreateDate(evaluateObject.getString("create_date"));
                        String user = evaluateObject.getString("playUser");
                        if (!"null".equals(user) && !"".equals(user)) {
                            JSONObject userObject = evaluateObject.getJSONObject("playUser");
                            member1.setMember_name(userObject.getString("user_name"));
                            member1.setMember_img(userObject.getString("user_photo"));
                        }else {
                            member1.setMember_name("");
                            member1.setMember_img("");
                        }
                        evaluateList.add(member1);
                    }
                    addBannerView();
                    initDate();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private void initDate(){
        tv_member_name.setText(member.getMember_name());
        if (member.getMember_address().equals("null")){
            member.setMember_address("");
        }
        tv_member_dizhi.setText("济宁/任城区");
        tv_member_duihao.setText(member.getClick_num() + "");

        ll_info_layout.removeAllViews();
        ImageView dotIv;
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(DensityUtils.dp2px(context, 40), DensityUtils.dp2px(context, 40));
        for (int i = 0; i < member.getGameImgs().size(); i++) {
            dotIv = new ImageView(context);
            //设置点的间距
            params.setMargins(DensityUtils.dp2px(context, 5), DensityUtils.dp2px(context, 5), 0,DensityUtils.dp2px(context, 5));
            dotIv.setLayoutParams(params);
            imageLoader.displayImage(ApiInterface.IMAGES + member.getGameImgs().get(i), dotIv, App.options);
            //添加点到view上
            ll_info_layout.addView(dotIv);
        }
        if (evaluateList.size() > 0){
            findViewById(R.id.ll_info_evaluate_all).setVisibility(View.VISIBLE);
            ll_info_evaluate.removeAllViews();
            View view;
            for (int i = 0; i < evaluateList.size(); i++) {
                view = LayoutInflater.from(context).inflate(R.layout.item_evaluate_lists, null);
                ImageView iv_item_info_user_img = (ImageView) view.findViewById(R.id.iv_item_info_user_img);
                TextView tv_item_info_user_name = (TextView) view.findViewById(R.id.tv_item_info_user_name);
                TextView tv_item_info_eval_time = (TextView) view.findViewById(R.id.tv_item_info_eval_time);
                TextView tv_item_info_eval = (TextView) view.findViewById(R.id.tv_item_info_eval);
                Member item = evaluateList.get(i);
                if (!item.getMember_img().equals("")) {
                    if (item.getMember_img().startsWith("http://wx.qlogo.cn/mmopen")) {
                        imageLoader.displayImage(item.getMember_img(), iv_item_info_user_img, App.options);
                    }else {
                        imageLoader.displayImage(ApiInterface.IMAGES + item.getMember_img(), iv_item_info_user_img, App.options);
                    }
                }
                tv_item_info_user_name.setText(item.getMember_name());
                tv_item_info_eval_time.setText(item.getCreateDate());
                tv_item_info_eval.setText(item.getEvaluateInfo());
                //添加点到view上
                ll_info_evaluate.addView(view);
            }
        }else {
            findViewById(R.id.ll_info_evaluate_all).setVisibility(View.GONE);
        }
    }

    public void addBannerView() {
        bannerListView.clear();
        if (member.getImgs().size() > 0) {
            bannerViewPager.setVisibility(View.VISIBLE);
            for (int i = 0; i < member.getImgs().size(); i++) {
                ImageView viewOne =  (ImageView) LayoutInflater.from(context).inflate(R.layout.b0_index_banner_cell, null);
                imageLoader.displayImage(ApiInterface.IMAGES + member.getImgs().get(i), viewOne, App.options);
                bannerListView.add(viewOne);
            }
            bannerPageAdapter.mListViews = bannerListView;
            bannerViewPager.setAdapter(bannerPageAdapter);
        }else {
            bannerViewPager.setVisibility(View.INVISIBLE);
        }
    }

    //获取屏幕宽度
    public int getDisplayMetricsWidth() {
        int i = getWindowManager().getDefaultDisplay().getWidth();
        int j = getWindowManager().getDefaultDisplay().getHeight();
        return Math.min(i, j);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUESTCODE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户同意了授权
                    call();
                } else {
                    //用户拒绝了授权
                }
                return;
            }
        }
    }

    private void call() {
        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + ApiInterface.PHONE));
        startActivity(intent);
    }

    private MyHttpClientRespenseHandler shieldingHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                try {
                    Integer isShielding =  json.getJSONObject("data").optInt("isShielding", 0);
                    if (isShielding == 1) {
                        tv_defriend.setText("取消拉黑");
                    }else {
                        tv_defriend.setText("拉黑");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler saveShieldingHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                tv_defriend.setText("取消拉黑");
            }
            String error_desc = json.optJSONObject("status").optString("error_desc");
            new ToastView(context, error_desc).show();
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler delShieldingHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                tv_defriend.setText("拉黑");
            }
            String error_desc = json.optJSONObject("status").optString("error_desc");
            new ToastView(context, error_desc).show();
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };


}
